package org.as.sdg.beans;

import java.util.HashMap;

import javax.swing.tree.DefaultTreeModel;

import org.as.sdg.builder.ApplicationBuilder;
import org.as.sdg.util.FacesUtils;

@SuppressWarnings("serial")
public class NavigationTreeFactory extends HashMap<String, DefaultTreeModel> {

	/**
	 * <p>
	 * Gets child tree model associated with this user session given the
	 * parentNodeId which must be a valid parent node id. The nodes are as
	 * defined in the application meta data.
	 * </p>
	 * <p>
	 * Once the tree is build it is added to the HashMap and the cached version
	 * is loaded on the next request.
	 * </p>
	 * 
	 * @param parentNodeId
	 *            nodeId of the meta data node in which we want to build a tree
	 *            on.
	 * @return tree model for the given node id's child elements. Can be passed
	 *         directing into a tree componetns value attribute.
	 */
	public DefaultTreeModel get(Object parentNodeId) {

		// check to see if the given tree model has been constructed.
		DefaultTreeModel childTreeModel = super.get(parentNodeId);

		// if not we build it and add it to our hash.
		if (childTreeModel == null) {

			// uses application builder to get us a tree for the given node id.
			ApplicationBuilder applicationBuilder = (ApplicationBuilder) FacesUtils
					.getManagedBean("applicationBuilder");

			childTreeModel = applicationBuilder
					.getChildNodeTree((String) parentNodeId);

			// cach the result for future reference
			this.put((String) parentNodeId, childTreeModel);
		}

		// finally return our node
		return childTreeModel;
	}
}